const matter = require("gray-matter");
const glob = require("glob");
const fs = require("fs");
const fse = require("fs-extra");

const path = require("path");

glob("snippets/*.md", { nodir: true }, function (er, files) {
  const markdonwText = `
  | 标题                                           | 标签 | 按钮                      |
  | ---------------------------------------------- | ---- | ------------------------- |
  `;

  let simpleMarkdownText = markdonwText;

  let middleMarkdownText = markdonwText;

  let advaceMarkdownText = markdonwText;

  const frontMatterArr = [];

  files.map((file) => {
    const buffer = fs.readFileSync(file);
    const item = matter(buffer);

    frontMatterArr.push({
      file,
      ...item.data,
    });
  });

  frontMatterArr.sort((a, b) => {
    return a.tags.localeCompare(b.tags);
  });

  frontMatterArr.map((item) => {
    const title = item.title;
    const tags = item.tags;
    const mipcode = item.mipcode ? item.mipcode : "";
    const expertise = item.expertise;
    const file = item.file;

    const appendMarkdown = `|[${title}](./${file})|${tags}| [Mipocde](${mipcode})|\n`;

    if (expertise == "初级") {
      simpleMarkdownText = simpleMarkdownText + appendMarkdown;
    } else if (expertise == "中级") {
      middleMarkdownText = middleMarkdownText + appendMarkdown;
    } else if (expertise == "高级") {
      advaceMarkdownText = advaceMarkdownText + appendMarkdown;
    } else {
      console.error("这是一条没有分等级的文档", title);
    }
  });

  const writeText = `
### 初级
    ${simpleMarkdownText}

### 中级
    ${middleMarkdownText}

### 高级
    ${advaceMarkdownText}
  `;

  fse.outputFileSync(path.resolve(process.cwd(), "./dir.md"), writeText);
});
